#include "git-remote-track-branch.h"

#include <git2/remote.h>

#include "util/strutil.h"

#include "git-ptr-holders.h"

namespace git
{

RemoteTrackBranch::RemoteTrackBranch(RemoteTrackBranch &&b)
    : Branch(std::move(b)) {
}

RemoteTrackBranch &RemoteTrackBranch::operator=(RemoteTrackBranch &&b) {
    Branch::operator=(std::move(b));
    return *this;
}

Remote RemoteTrackBranch::remote() const {
    RemoteHolder r;
    git_remote_lookup(r.visit(), repo(), remoteName().c_str());
    return Remote(r.take());
}

RemoteTrackBranch::RemoteTrackBranch(git_reference *ref)
    : Branch(ref) {
}

std::string RemoteTrackBranch::remoteName() const {
    const strutil::strviews parts = strutil::split(fullname(), '/');
    // branch full name should look like: "refs/remotes/origin/master"
    // general form is "refs/remotes/{remote}/{branch}"
    if (parts.size() != 4) {
        return std::string();
    }
    if (parts[0] != "refs" || parts[1] != "remotes") {
        return std::string();
    }
    return std::string(parts[2]);
}

} // namespace git
